package main

import (
	"context"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"net/http"
	"os"
	"os/signal"
	"queue-gateway/K8Sapi"
	"queue-gateway/router"
	"queue-gateway/tokenBuket"
	"syscall"
	"time"
)

func initLog() {
	levelStr := os.Getenv("LOG_LEVEL")
	if levelStr != "" {
		level, err := log.ParseLevel(levelStr)
		if err != nil {
			level = log.InfoLevel
		}
		log.SetLevel(level) //设置日志的显示级别，这一级别以及更高级别的日志信息将会输出
	}
	//log.SetFormatter(&log.JSONFormatter{}) //设置日志的输出格式为json格式，还可以设置为text格式
	log.SetOutput(os.Stdout) //设置日志的输出为标准输出
}

func main() {
	initLog()
	ctx, cancel := context.WithCancel(context.Background())
	err := K8Sapi.WatchInit(ctx)
	go tokenBuket.ReleaseToken(ctx)
	defer cancel()
	if err != nil {
		panic(err)
	}
	// 创建一个默认的路由引擎
	//engine := gin.Default()
	//router.ApiRegister(engine)
	//
	//// 启动HTTP服务，默认在0.0.0.0:8080启动服务
	//engine.Run(":8090")

	ginInit()
}

// 带优雅重启的GIN初始化封装方式
func ginInit() {
	port := "8080"
	engin := gin.Default()
	router.ApiRegister(engin)

	srv := &http.Server{
		Addr:    fmt.Sprintf(":%s", port),
		Handler: engin,
	}

	// Initializing the server in a goroutine so that
	// it won't block the graceful shutdown handling below
	go func() {
		if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	// Wait for interrupt signal to gracefully shutdown the server with
	quit := make(chan os.Signal)
	// kill (no param) default send syscall.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutting down server...")

	// The context is used to inform the server it has 'timeout' seconds to finish
	// the request it is currently handling
	timeout := 30
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
	//errWatchInit := K8Sapi.WatchInit(ctx)
	//if errWatchInit != nil {
	//	log.Fatal("K8S watcher init failed!")
	//}
	//go tokenBuket.ReleaseToken(ctx)

	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server forced to shutdown:", err)
	}

	// catching ctx.Done(). timeout of timeout seconds.
	select {
	case <-ctx.Done():
		log.Println(fmt.Sprintf("timeout of %v seconds.", timeout))
	}
	log.Println("Server exiting")
}
